const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = db.command;

// 获取用户信息
async function getUserInfo(userId) {
  try {
    const rs = await db.collection('users').where({ _openid: userId }).limit(1).get();
    if (rs.data && rs.data[0]) {
      const u = rs.data[0];
      return {
        openId: userId,
        nickName: u.nickName || '学习伙伴',
        avatarUrl: u.avatarUrl || u.avatar_url || '/assets/icons/avatar-placeholder.png'
      };
    }
    // 未找到用户记录时，返回默认信息（不创建文档）
    return {
      openId: userId,
      nickName: '学习伙伴',
      avatarUrl: '/assets/icons/avatar-placeholder.png'
    };
  } catch (error) {
    console.error('获取用户信息出错:', error);
    return {
      openId: userId,
      nickName: '学习伙伴',
      avatarUrl: '/assets/icons/avatar-placeholder.png'
    };
  }
}

/**
 * 生成时间槽键值（与前端/轮询一致：相对当前时间判断是否跨天）
 * 同步到 checkMatchingStatus / checkMatchStatus，保证统一
 */
function generateTimeSlotKey(startTime, endTime) {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  const currentTotalMinutes = currentHour * 60 + currentMinute;

  const [startHour, startMinute] = startTime.split(':').map(Number);
  const [endHour, endMinute] = endTime.split(':').map(Number);
  const startTotalMinutes = startHour * 60 + startMinute;
  const endTotalMinutes = endHour * 60 + endMinute;

  // 确定开始日期
  let startDate;
  if (startTotalMinutes <= currentTotalMinutes) {
    // 开始时间 <= 当前时间 → 次日
    startDate = new Date(now.getTime() + 24 * 60 * 60 * 1000);
  } else {
    // 开始时间 > 当前时间 → 当天
    startDate = now;
  }

  // 确定结束日期
  let endDate;
  if (endTotalMinutes <= startTotalMinutes) {
    // 结束时间 <= 开始时间，说明跨天到下一天
    endDate = new Date(startDate.getTime() + 24 * 60 * 60 * 1000);
  } else {
    // 结束时间 > 开始时间，同一天
    endDate = startDate;
  }

  const startDateStr = startDate.toISOString().split('T')[0];
  const endDateStr = endDate.toISOString().split('T')[0];

  // 生成包含完整日期信息的键值
  if (startDateStr === endDateStr) {
    // 同一天
    return `${startDateStr}_${startTime}-${endTime}`;
  } else {
    // 跨天
    return `${startDateStr}_${startTime}-${endDateStr}_${endTime}`;
  }
}

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  
  if (!userId) {
    return {
      code: 401,
      message: '用户未登录'
    };
  }

  const { startTime, endTime, studyDuration } = event;
  
  if (!startTime || !endTime || !studyDuration) {
    return {
      code: 400,
      message: '参数不完整'
    };
  }

  try {
    console.log('开始匹配处理，用户ID:', userId);
    console.log('匹配参数:', { startTime, endTime, studyDuration });
    
    // 生成时间槽键值
    const timeSlotKey = generateTimeSlotKey(startTime, endTime);
    console.log('生成的时间槽键值:', timeSlotKey);

    // 检查用户是否已在匹配池中
    const existingPool = await db.collection('matching_pool')
      .where({ userId })
      .get();

    if (existingPool.data.length > 0) {
      // 移除用户之前的匹配池记录（逐条删除，CloudBase 无 db.batch）
      await Promise.all(
        existingPool.data.map(record =>
          db.collection('matching_pool').doc(record._id).remove()
        )
      );
      console.log('清理用户之前的匹配池记录');
    }

    // 查找匹配池中的其他用户
    const waitingUsers = await db.collection('matching_pool')
      .where({ 
        timeSlotKey,
        userId: _.neq(userId)
      })
      .limit(1)
      .get();

    console.log('查找到的等待用户数量:', waitingUsers.data.length);

    if (waitingUsers.data.length > 0) {
      // 找到匹配用户，创建学习记录
      const matchedUser = waitingUsers.data[0];
      console.log('找到匹配用户:', matchedUser.userId);
      
      // 生成唯一的匹配ID
      const matchId = `match_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      console.log('生成匹配ID:', matchId);
      
      // 获取当前用户信息
      const currentUserInfo = await getUserInfo(userId);
      console.log('当前用户信息:', currentUserInfo);
      
      // 创建两条学习记录
      console.log('开始创建学习记录，matchId:', matchId);
      console.log('当前用户ID:', userId);
      console.log('匹配用户ID:', matchedUser.userId);
      
      const [studyRecord1, studyRecord2] = await Promise.all([
        db.collection('study_records').add({
          data: {
            userId,
            matchId,
            startTime,
            endTime,
            duration: studyDuration,
            status: 'not_started',
            createTime: new Date(),
            updateTime: new Date(),
          }
        }),
        db.collection('study_records').add({
          data: {
            userId: matchedUser.userId,
            matchId,
            startTime,
            endTime,
            duration: studyDuration,
            status: 'not_started',
            createTime: new Date(),
            updateTime: new Date(),
          }
        })
      ]);
      
      console.log('学习记录创建结果:');
      console.log('- studyRecord1._id:', studyRecord1._id);
      console.log('- studyRecord2._id:', studyRecord2._id);
      console.log('- matchId:', matchId);
      
      // 从匹配池移除对方
      await db.collection('matching_pool').doc(matchedUser._id).remove();
      console.log('已从匹配池移除匹配用户');
      
      const responseData = {
        matched: true,
        studyRecordId: studyRecord1._id,
        matchId,
        matchTime: {
          startTime,
          endTime,
          duration: studyDuration
        },
        timeSlotKey
      };
      
      console.log('返回的响应数据:', responseData);
      
      return {
        code: 0,
        message: '匹配成功',
        data: responseData
      };
    } else {
      // 没有找到匹配用户，加入匹配池等待
      console.log('没有找到匹配用户，加入匹配池等待');
      
      const userInfo = await getUserInfo(userId);
      console.log('用户信息:', userInfo);
      
      const expireTime = new Date(Date.now() + 30 * 60 * 1000); // 30分钟后过期
      
      const poolRecord = await db.collection('matching_pool').add({
        data: {
          timeSlotKey,
          userId,
          userInfo,
          studyDuration,
          joinTime: new Date(),
          expireAt: expireTime
        }
      });
      
      console.log('已加入匹配池，记录ID:', poolRecord._id);
      
      return {
        code: 0,
        message: '已加入匹配池，等待匹配',
        data: {
          matched: false,
          status: 'waiting',
          timeSlotKey,
          expireAt: expireTime
        }
      };
    }
  } catch (error) {
    console.error('匹配处理失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      error: error.message
    };
  }
};